package com.pwrd.sframe.core.thread;

import com.pwrd.sframe.support.log.Log;
import com.pwrd.sframe.support.util.Stopwatch;

/**
 * @Auther syc.
 * @Date 2017/1/22 16:56.
 */
public class ThreadHandler extends Thread{

    private RunnableCase runCase;

    private Stopwatch stopwatch;

    // 心跳间隔（毫秒）
    private long interval = 20;

    // 线程是否正在运行
    private volatile boolean running = false;

    public ThreadHandler(RunnableCase runCase, String name) {
        super(name);
        this.runCase = runCase;
        stopwatch = Stopwatch.createUnstarted();
    }

    public void startup() {
        if(running) {
            return;
        }
        start();
        running = true;
    }

    public void cleanup() {
        if(!running) return;
        running = false;
    }

    @Override
    public void run() {
        while (running) {

            try {
                stopwatch.resetAndStart();
                // 心跳
                pulse();

                stopwatch.stop();

                if(stopwatch.lastTime() < interval) {
                    sleep(interval - stopwatch.lastTime());
                }
            } catch (Exception e) { // Q：与抛出Throwable的区别(Java本身设计思路就是希望大家catch Exception就足够了，如果有Error发生，catch了也不会有什么作用)
                Log.core.error("", e);
            }
        }
    }

    private void pulse() {
        runCase.run();
    }
}
